package com.hht.toolanduilibs.widget

import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbManager
import android.net.ConnectivityManager
import android.net.wifi.WifiManager
import android.os.Build
import android.util.AttributeSet
import android.widget.LinearLayout
import androidx.annotation.RequiresApi
import com.hht.toolanduilibs.util.StateDetectionUtils


/**
 * Author:chen'hu
 * Time:2023/8/7 10:55
 * Description:This is StateBarView
 */
abstract class StateBarView : LinearLayout {
    var isNetConnect = false
    private var isWiFiConnect = false
    private var netReceiver: NetReceiver? = null
    private var btReceiver: BluetoothReceiver? = null
    private var hotSpotReceiver: HotSpotReceiver? = null
    private var usbReceiver: UsbReceiver? = null
    private var notificationReceiver: NotificationReceiver? = null

    companion object {
        private const val WIFI_AP_STATE_CHANGED_ACTION: String =
            "android.net.wifi.WIFI_AP_STATE_CHANGED"
        private const val NOTIFICATION_IS_UPDATE_KEY = "persist.sys.is.update"
        private const val NOTIFICATION_ACTION_UPDATE = "com.hht.action.update.prompt"
        private lateinit var context: Context
    }

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0)

    @SuppressLint("NewApi")
    constructor(context: Context, attributeSet: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attributeSet,
        defStyleAttr
    ) {
        Companion.context = context
    }

    protected abstract fun updatePowerOffState(showView: Boolean)
    protected abstract fun updateInterNetState(internetState: Boolean)
    protected abstract fun updateWifiState(wifiState: Boolean, level: Int)
    protected abstract fun updateBluetoothState(btState: Boolean)
    protected abstract fun updateHotSpotState(hotState: Boolean)
    protected abstract fun updateUsbState(usbState: Boolean)
    protected abstract fun updateNotificationState(notifyState: Boolean)

    private fun registerAllReceiver() {
        registerNetReceiver()
        registerBluetoothReceiver()
        registerHotSpotReceiver()
        registerUsbReceiver()
        registerNotificationReceiver()
    }

    /**
     * 注册广播接受者
     */
    private fun unRegisterAllReceiver() {
        try {
            if (netReceiver != null) {
                context.unregisterReceiver(netReceiver)
                netReceiver = null
            }
            if (btReceiver != null) {
                context.unregisterReceiver(btReceiver)
                btReceiver = null
            }
            if (hotSpotReceiver != null) {
                context.unregisterReceiver(hotSpotReceiver)
                hotSpotReceiver = null
            }
            if (usbReceiver != null) {
                context.unregisterReceiver(usbReceiver)
                usbReceiver = null
            }
            if (notificationReceiver != null) {
                context.unregisterReceiver(notificationReceiver)
                notificationReceiver = null
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        registerAllReceiver()
    }

    override fun onDetachedFromWindow() {
        unRegisterAllReceiver()
        super.onDetachedFromWindow()
    }


    /**
     * 更新所有View的状态
     */
    @RequiresApi(Build.VERSION_CODES.N)
    fun updateStateView() {
        updatePowerOffState()
        updateBluetoothState()
        updateHotSpotState()
        updateUsbState()
        updateNotificationState()
        updateNetState()
    }


    //TODO 在xml里面如果直接写visible,会出现二个图标的bug
    private fun updatePowerOffState() {
        updatePowerOffState(showPowerOffIcon())
    }

    protected fun showPowerOffIcon(showPowerOffIcon: Boolean = false): Boolean {
        return showPowerOffIcon
    }


    /**
     * 更新通知状态
     */
    private fun updateNotificationState() {
        updateNotificationState(
            StateDetectionUtils.isHaveNotification(
                context,
                NOTIFICATION_IS_UPDATE_KEY
            )
        )
    }

    /**
     * 注册通知相关监听广播
     */
    private fun registerNotificationReceiver() {
        if (notificationReceiver == null) {
            notificationReceiver = NotificationReceiver()
            val notificationFilter = IntentFilter()
            notificationFilter.addAction(NOTIFICATION_ACTION_UPDATE)
            context.registerReceiver(notificationReceiver, notificationFilter)
        }
    }

    private inner class NotificationReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            updateNotificationState()
        }
    }

    /**
     * 更新usb状态
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private fun updateUsbState() {
        updateUsbState(StateDetectionUtils.isUsbMount(context))
    }

    /**
     * 注册usb相关监听广播
     */
    private fun registerUsbReceiver() {
        if (usbReceiver == null) {
            usbReceiver = UsbReceiver()
            val usbFilter = IntentFilter()
            usbFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
            usbFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
            usbFilter.addAction(Intent.ACTION_MEDIA_EJECT)
            usbFilter.addAction(Intent.ACTION_MEDIA_MOUNTED)
            usbFilter.addAction(Intent.ACTION_MEDIA_REMOVED)
            usbFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED)
            usbFilter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL)
            usbFilter.addDataScheme("file")
            context.registerReceiver(usbReceiver, usbFilter)
        }
    }

    /**
     * usb状态广播接受者
     */
    private inner class UsbReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            if (UsbManager.ACTION_USB_DEVICE_ATTACHED == action ||
                Intent.ACTION_MEDIA_MOUNTED == action
            ) {
                updateUsbState(StateDetectionUtils.isUsbMount(context))
            } else if (UsbManager.ACTION_USB_DEVICE_DETACHED == action ||
                Intent.ACTION_MEDIA_UNMOUNTED == action ||
                Intent.ACTION_MEDIA_REMOVED == action ||
                Intent.ACTION_MEDIA_EJECT == action /*||
                Intent.ACTION_MEDIA_BAD_REMOVAL.equalsIgnoreCase(action)*/) {
                updateUsbState(StateDetectionUtils.isUsbMount(context))
            }
        }
    }


    /**
     * 更新热点状态
     */
    private fun updateHotSpotState() {
        updateHotSpotState(StateDetectionUtils.getHotSpotState(context))
    }

    /**
     * 注册热点状态监听广播
     */
    private fun registerHotSpotReceiver() {
        if (hotSpotReceiver == null) {
            hotSpotReceiver = HotSpotReceiver()
            val hotFilter = IntentFilter()
            hotFilter.addAction(WIFI_AP_STATE_CHANGED_ACTION)
            context.registerReceiver(hotSpotReceiver, hotFilter)
        }
    }

    /**
     * 热点状态广播接受者
     */
    private inner class HotSpotReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            //便携式热点的状态为：10:正在关闭; 11:已关闭; 12:正在开启; 13:已开启
            val state = intent.getIntExtra("wifi_state", 0)
            if (state == 13) {
                updateHotSpotState(true)
            } else {
                updateHotSpotState(false)
            }
        }
    }


    /**
     * 更新蓝牙状态
     */
    @RequiresApi(Build.VERSION_CODES.ECLAIR)
    private fun updateBluetoothState() {
        updateBluetoothState(StateDetectionUtils.getBluetoothState(context))
    }

    /**
     * 注册蓝牙状态监听广播
     */
    private fun registerBluetoothReceiver() {
        if (btReceiver == null) {
            btReceiver = BluetoothReceiver()
            val btFilter = IntentFilter()
            btFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
            context.registerReceiver(btReceiver, btFilter)
        }
    }

    /**
     * 蓝牙状态广播接受者
     */
    private inner class BluetoothReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            when (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0)) {
                BluetoothAdapter.STATE_OFF -> updateBluetoothState(false)
                BluetoothAdapter.STATE_ON -> updateBluetoothState(true)
            }
        }
    }


    /**
     * 更新网络状态
     */
    private fun updateNetState() {
        isNetConnect = StateDetectionUtils.isEthernetConnecting(context)
        updateInterNetState(isNetConnect)
        isWiFiConnect = StateDetectionUtils.isWifiConnecting(context)
        updateWifiState(isWiFiConnect, StateDetectionUtils.getWifiSignalLevel(context))
    }

    /**
     * 注册网络相关监听广播
     */
    private fun registerNetReceiver() {
        if (netReceiver == null) {
            netReceiver = NetReceiver()
            val netFilter = IntentFilter()
            netFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
            netFilter.addAction(WifiManager.RSSI_CHANGED_ACTION)
            context.registerReceiver(netReceiver, netFilter)
        }
    }

    private inner class NetReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent) {

            context?.let {
                if (intent.action == ConnectivityManager.CONNECTIVITY_ACTION) {
                    val internetTemp: Boolean = StateDetectionUtils.isEthernetConnecting(it)
                    val wifiTemp: Boolean = StateDetectionUtils.isWifiConnecting(it)
                    if (isNetConnect != internetTemp) {
                        isNetConnect = internetTemp
                        updateInterNetState(isNetConnect)
                    }
                    if (isWiFiConnect != wifiTemp) {
                        isWiFiConnect = wifiTemp
                        updateWifiState(isWiFiConnect, StateDetectionUtils.getWifiSignalLevel(it))
                    }
                } else if (intent.action == WifiManager.RSSI_CHANGED_ACTION) { //监听WiFi信号强度变化
                    updateWifiState(isWiFiConnect, StateDetectionUtils.getWifiSignalLevel(it))
                }
            }
        }
    }

}
